package com.monkeyboy.mongo_demo;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.monkeyboy.util.MongoDBAuthUtil;
import org.bson.Document;

import java.util.Arrays;

/**
 * 更新文档
 *
 * @Author Gavin
 * @date 2021.01.10 17:54
 */
public class UpdateDocument {
    public static void main(String[] args) {
        UpdateDocument updateDocument = new UpdateDocument();
        updateDocument.updateDocumentArray();
    }
    /**
     * 更新文档中的数组
     */
    public void updateDocumentArray(){
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        collection.updateOne(Filters.eq("username","test"),new Document("$push",new Document("tags","php")));
    }

    /**
     * 更新多个文档的多个键
     */
    public void updateManyDocumentManyKey() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        collection.updateMany(Filters.ne("username", "Gavin"), new Document("$set", new Document("username", "llq").append("age", 33)));
    }

    /**
     * 更新多个文档的单个键
     */
    public void updateManyDocumentSingleKey() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        collection.updateMany(Filters.eq("username", null), new Document("$set", new Document("username", "Gavin")));
    }

    /**
     * 更新单个文档的多个键
     */
    public void updateSingleDocumentManyKey() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        collection.updateOne(Filters.eq("username", "llq"), new Document("$set", new Document("age", 28).append("tags", Arrays.asList("java", "go", "python"))));
    }

    /**
     * 更新单个文档单个键
     */
    public void updateSingleDocumentSingleKey() {
        MongoCollection<Document> collection = MongoDBAuthUtil.getCollection("test", "java_coll");
        //更新文档{$set:{}}
        //Filters封装了条件筛选
        collection.updateOne(Filters.eq("username", "llq"), new Document("$set", new Document("age", 28)));
    }
}
